package config

import (
	cryptorand "crypto/rand"
	"encoding/hex"
	"encoding/json"
	"io/ioutil"
	"log"
	"math/big"
	"os"
	"time"
)

// DefaultConfig 返回默认配置
func DefaultConfig() *Config {
	return &Config{
		Sensor: SensorConfig{
			Ports: map[string]SensorPortConfig{
				"/dev/ttyCH9344USB0": {
					SensorID:   "TEMP_SENSOR",
					Type:       "temperature",
					DataLength: 18,
				},
				"/dev/ttyCH9344USB1": {
					SensorID:   "CO_SENSOR",
					Type:       "co",
					DataLength: 9,
				},
				"/dev/ttyCH9344USB2": {
					SensorID:   "CO2_SENSOR",
					Type:       "co2",
					DataLength: 6,
				},
				"/dev/ttyCH9344USB3": {
					SensorID:   "SMOKE_SENSOR",
					Type:       "smoke",
					DataLength: 9,
				},
				"/dev/ttyCH9344USB4": {
					SensorID:   "CONDUCTIVITY_SENSOR",
					Type:       "conductivity",
					DataLength: 6,
				},
				"/dev/ttyCH9344USB5": {
					SensorID:   "LIQUID_LEVEL_SENSOR",
					Type:       "liquid_level",
					DataLength: 9,
				},
			},
			BaudRate:     9600,
			ReadInterval: 1 * time.Second, // 优化：从100ms改为1秒，降低读取频率
			BufferSize:   128,
		},
		Server: ServerConfig{
			BaseURL: "http://127.0.0.1:8001",
		},
		HealthCheck: HealthConfig{
			HealthCheckInterval: 5 * time.Second,
			ReadyCheckInterval:  5 * time.Second,
		},
		MQTT: MQTTConfig{
			Enabled:  true,                  // 默认启用 MQTT
			Broker:   "ssl://127.0.0.1:8883", // 使用TLS加密连接
			Username: "device",              // 可选
			QoS:      1,                     // QoS 1（至少一次）
			Retained: false,                 // 不保留消息
			TLS: MQTTTLSConfig{
				Enabled:            true,                        // 启用TLS
				CAFile:             "./config/certs/ca.crt",     // CA证书
				CertFile:           "./config/certs/client.crt", // 客户端证书（可选）
				KeyFile:            "./config/certs/client.key", // 客户端私钥（可选）
				InsecureSkipVerify: false,                       // 完整证书验证
			},
		},
	}
}

// 加载传感器设备配置数组
func LoadSensorDeviceConfigs() SensorDeviceConfigs {
	configFile := "device_config.json"
	log.Printf("尝试加载传感器配置文件: %s", configFile)

	if _, err := os.Stat(configFile); err == nil {
		log.Println("传感器配置文件存在，读取内容...")
		data, err := ioutil.ReadFile(configFile)
		if err != nil {
			log.Printf("读取传感器配置文件失败: %v", err)
			return CreateDefaultSensorDeviceConfigs()
		}

		var configs SensorDeviceConfigs
		if err := json.Unmarshal(data, &configs); err != nil {
			log.Printf("解析传感器配置文件失败: %v", err)
			return CreateDefaultSensorDeviceConfigs()
		}

		log.Printf("传感器配置文件加载成功，共 %d 个传感器", len(configs))
		return configs
	}

	log.Println("传感器配置文件不存在，创建默认配置")
	return CreateDefaultSensorDeviceConfigs()
}

// 加载设备配置（保持向后兼容）
func LoadDeviceConfig() DeviceConfig {
	// 从传感器配置数组中获取第一个设备的基本信息
	sensorConfigs := LoadSensorDeviceConfigs()
	if len(sensorConfigs) == 0 {
		return CreateDefaultConfig()
	}

	// 使用第一个传感器的基本信息
	firstSensor := sensorConfigs[0]
	defaultConfig := DefaultConfig()

	return DeviceConfig{
		DeviceID:    firstSensor.DeviceID,
		Secret:      firstSensor.Secret,
		Commitment:  firstSensor.Commitment,
		Registered:  firstSensor.Registered,
		ConfigFile:  firstSensor.ConfigFile,
		Sensor:      defaultConfig.Sensor,
		Server:      defaultConfig.Server,
		HealthCheck: defaultConfig.HealthCheck,
		MQTT:        defaultConfig.MQTT,
	}
}

// 创建默认传感器设备配置数组
func CreateDefaultSensorDeviceConfigs() SensorDeviceConfigs {
	log.Println("创建默认传感器设备配置")

	// 定义7种传感器的默认配置（根据实际连接）
	sensorConfigs := []struct {
		deviceID    string
		sensorType  string
		port        string
		dataLength  int
		description string
	}{
		{"TEMP_SENSOR", "temperature", "/dev/ttyCH9344USB0", 18, "温度传感器"},
		{"CO_SENSOR", "co", "/dev/ttyCH9344USB1", 9, "一氧化碳传感器"},
		{"CO2_SENSOR", "co2", "/dev/ttyCH9344USB2", 6, "二氧化碳传感器"},
		{"SMOKE_SENSOR", "smoke", "/dev/ttyCH9344USB3", 9, "烟雾传感器"},
		{"CONDUCTIVITY_SENSOR", "conductivity", "/dev/ttyCH9344USB4", 6, "电导率传感器"},
		{"LIQUID_LEVEL_SENSOR", "liquid_level", "/dev/ttyCH9344USB5", 9, "液位传感器"},
		{"FLOW_SENSOR", "flow", "/dev/ttyCH9344USB6", 7, "流速传感器"},
	}

	var configs SensorDeviceConfigs

	// ✅ 修复：为每个传感器生成独立的secret
	for _, sensor := range sensorConfigs {
		secret := GenerateRandomSecret()
		log.Printf("[%s] 生成独立密钥: %s", sensor.deviceID, secret)

		config := SensorDeviceConfig{
			DeviceID:    sensor.deviceID,
			Secret:      secret,
			Commitment:  "",
			Registered:  false,
			ConfigFile:  "device_config.json",
			SensorType:  sensor.sensorType,
			Port:        sensor.port,
			DataLength:  sensor.dataLength,
			Description: sensor.description,
		}
		configs = append(configs, config)
	}

	return configs
}

// 创建默认配置（保持向后兼容）
func CreateDefaultConfig() DeviceConfig {
	log.Println("创建默认配置")
	// 生成 32 字节随机 secret (hex 编码为 64 字符)
	secret := GenerateRandomSecret()
	log.Printf("生成的随机密钥: %s", secret)

	// 获取默认的完整配置
	defaultConfig := DefaultConfig()

	return DeviceConfig{
		DeviceID:    "TEMP_SENSOR",
		Secret:      secret,
		Commitment:  "",
		Registered:  false,
		ConfigFile:  "device_config.json",
		Sensor:      defaultConfig.Sensor,
		Server:      defaultConfig.Server,
		HealthCheck: defaultConfig.HealthCheck,
		MQTT:        defaultConfig.MQTT,
	}
}

// 生成随机密钥
// ✅ 修复: 确保生成的 secret 在 BN254 scalar field 范围内
func GenerateRandomSecret() string {
	log.Println("生成随机密钥...")

	// BN254 scalar field 模数 (约 254 位)
	modulus, _ := new(big.Int).SetString("21888242871839275222246405745257275088548364400416034343698204186575808495617", 10)

	// 生成随机数并确保在域范围内
	for {
		b := make([]byte, 32)
		if _, err := cryptorand.Read(b); err != nil {
			log.Printf("生成随机密钥失败: %v", err)
			return "default_secret_" + time.Now().Format("20060102150405")
		}

		// 检查是否小于模数
		secretBig := new(big.Int).SetBytes(b)
		if secretBig.Cmp(modulus) < 0 {
			// 在域范围内，使用这个 secret
			log.Println("✅ 生成的密钥在 BN254 域范围内")
			return hex.EncodeToString(b)
		}
		// 否则重新生成
		log.Println("⚠️  生成的密钥超过域范围，重新生成...")
	}
}

// 保存传感器设备配置数组
func SaveSensorDeviceConfigs(configs SensorDeviceConfigs) {
	if len(configs) == 0 {
		log.Println("传感器配置为空，跳过保存")
		return
	}

	log.Printf("保存传感器设备配置，共 %d 个传感器", len(configs))
	data, err := json.MarshalIndent(configs, "", "  ")
	if err != nil {
		log.Printf("序列化传感器配置失败: %v", err)
		return
	}

	configFile := "device_config.json"
	if err := ioutil.WriteFile(configFile, data, 0644); err != nil {
		log.Printf("保存传感器配置文件失败: %v", err)
	} else {
		log.Printf("传感器配置已保存到 %s", configFile)
	}
}

// 保存设备配置（保持向后兼容）
func SaveDeviceConfig(config DeviceConfig) {
	log.Printf("保存设备配置: %+v", config)
	data, err := json.MarshalIndent(config, "", "  ")
	if err != nil {
		log.Printf("序列化配置失败: %v", err)
		return
	}

	if err := ioutil.WriteFile(config.ConfigFile, data, 0644); err != nil {
		log.Printf("保存配置文件失败: %v", err)
	}
}

// LoadConfigFromDeviceConfig 从设备配置中提取完整配置
func LoadConfigFromDeviceConfig() *Config {
	deviceConfig := LoadDeviceConfig()

	return &Config{
		Sensor:      deviceConfig.Sensor,
		Server:      deviceConfig.Server,
		HealthCheck: deviceConfig.HealthCheck,
		MQTT:        deviceConfig.MQTT,
	}
}
